package com.youlu.campus.service.platform.impl;

import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.entity.platform.PlatformSubConfigure;
import com.youlu.campus.service.platform.PlatformSubConfigureService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
public class PlatformSubConfigureServiceImpl implements PlatformSubConfigureService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public PlatformSubConfigure findByAppId(String appId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("appId").is(appId));
        return mongoTemplate.findOne(query, PlatformSubConfigure.class);
    }

    @Override
    public boolean create(@NotNull PlatformSubConfigure req) {
        req.setId(null);
        req.setCreatedTime(new Date());
        req = mongoTemplate.insert(req);
        if (StringUtils.isNotBlank(req.getId())) {
            return true;
        }
        return false;
    }

    @Override
    public boolean update(@NotNull PlatformSubConfigure req) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(req.getId()));
        Update update = new Update();
        boolean toUpdate = false;
        if (Objects.nonNull(req.getAppId())) {
            update.set("appId", req.getAppId());
            toUpdate = true;
        }
        if (Objects.nonNull(req.getEnable())) {
            update.set("enable", req.getEnable());
            toUpdate = true;
        }
        if (Objects.nonNull(req.getSubOpen())) {
            update.set("subOpen", req.getSubOpen());
            toUpdate = true;
        }
        if (StringUtils.isNotBlank(req.getTemplateIds())) {
            update.set("templateIds", req.getTemplateIds());
            toUpdate = true;
        }
        if (toUpdate) {
            UpdateResult updateResult = mongoTemplate.updateFirst(query, update, PlatformSubConfigure.class);
            return updateResult.getModifiedCount() > 0 ? true : false;
        }
        return true;

    }
}
